﻿//
// Created by QU on 24-9-28.
//

#ifndef LOGIC_SYSTEM_H
#define LOGIC_SYSTEM_H

#include <mutex>
#include <memory>
#include <queue>
#include <map>
#include <condition_variable>
#include <thread>
#include <functional>

#include "server/logic/MSGID.h"
#include "server/public/Singleton.hpp"
#include "server/logic/LogicNode.h"

class LogicSystem : public Singleton<LogicSystem>
{
    constexpr static size_t WORKER_THREAD_COUNT = 2;


    friend class Singleton<LogicSystem>;

public:
    using CallBackFunc = std::function<void (std::shared_ptr<LogicNode> logic_node)>;

    void helloWorldCallBack(const std::shared_ptr<LogicNode>& logic_node);
    void postNodeToQueue(const std::shared_ptr<LogicNode>& node);
    void callBackRegister(MSGID msg_id, const CallBackFunc& func);

    void registAllCallbacks();

private:
    explicit LogicSystem(size_t worker_count = WORKER_THREAD_COUNT);
    ~LogicSystem();
    void startWorker(size_t worker_count);
    void stopWorker();

    void workerThreadFunc(const std::stop_token& stop_token);
    void logicNodeDispatcher(const std::shared_ptr<LogicNode>& logic_node);

    std::queue<std::shared_ptr<LogicNode>> m_logic_node_queue;
    std::mutex m_mutex;
    std::condition_variable m_condition;
    std::vector<std::jthread> m_worker_threads;
    std::map<uint8_t, CallBackFunc> m_callback_map;
};

#endif // LOGIC_SYSTEM_H
